//
//  OAuthViewController.swift
//  weibopush
//
//  Created by 龚欣 on 15/6/25.
//  Copyright © 2015年 gong. All rights reserved.
//

import UIKit
import SVProgressHUD
class OAuthViewController: UIViewController,UIWebViewDelegate {

    lazy var webView : UIWebView = {
            let w = UIWebView()
            w.delegate = self
            return w
        }()
    
    
    let WB_Client_ID = "3129943327"
    let WB_Client_Secret = "0b780c4d2c09e42ac84c316b7a413339"
    let WB_Redirect_URL = "http://www.baidu.com"
/**
    App Key：3885140363
    App Secret：ec1ac4f2d37b8a1f627969c262773cb3
    http://www.baidu.com

*/
    
    override func viewDidLoad() {
        super.viewDidLoad()
        loadLogin()
    }

    override func loadView() {

        view = webView
        title = "登陆"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    
    func close(){
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func loadLogin(){
    //https://api.weibo.com/oauth2/authorize?client_id=3885140363&redirect_uri=http://www.baidu.com
        let URLString = "https://api.weibo.com/oauth2/authorize?client_id=\(WB_Client_ID)&redirect_uri=\(WB_Redirect_URL)"
        let URL = NSURL(string: URLString)!
        let request = NSURLRequest(URL: URL)
        webView.loadRequest(request)
    
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString = request.URL!.absoluteString
        //如果不是回调的URL就继续加载
        if !urlString.hasPrefix(WB_Redirect_URL){
            return true
        }
        print("需要判断")
        let query = request.URL!.query!
        
        let codeStr = "code="
        if query.hasPrefix(codeStr){
            //获取授权码
            let code = query.substringFromIndex(advance(codeStr.endIndex, 0))
            print("获取授权码\(code)")
            loadAccessToken(code)
        }else{
            print("取消授权")
            close()
        }
        return false
    }
    
    func loadAccessToken(code : String){
        //https://api.weibo.com/oauth2/access_token

        let URLString = "oauth2/access_token"
        let params = ["client_id" : WB_Client_ID,
            "client_secret" : WB_Client_Secret,
            "grant_type" : "authorization_code",
            "code" : code,
            "redirect_uri" : WB_Redirect_URL]
        
        //获取数据的时候如果崩了很有可能是接口文档的数据格式发生了变化
        NetworkTool.sharedNetworkTool().POST(URLString, parameters: params, success: { (_, JSON) -> Void in
            print(JSON)
            let dict = JSON as! [String : NSObject]
            let useraccount = UserAccount(dict: dict) as UserAccount
            useraccount.loadUserInfo { (account, error) -> () in
                //如果账号不为空，表示账号授权成功，只有授权成功才有下面步骤
                if account != nil{
                    sharedAccount = account
                   NSNotificationCenter.defaultCenter().postNotificationName("SwitchRootViewControllerNotification", object: false)
                    self.close()
                    return
                }
                print(error)
                SVProgressHUD.showInfoWithStatus("您的网不给力")
            }
            }) { (_, error) -> Void in
                print(error)
                SVProgressHUD.showInfoWithStatus("您的网不给力")
        }
    }


}
